package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.UserExistException;
import com.atguigu.gulimall.member.service.MemberLevelService;
import com.atguigu.gulimall.member.vo.MemberLoginVO;
import com.atguigu.gulimall.member.vo.MemberRegistVO;
import com.atguigu.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVO memberRegistVO) {

        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = new MemberEntity();

        //设置默认登记
        entity.setLevelId(1L);
        //校验用户名,手机号唯一性 为了让controller感知异常 使用异常机制
        checkUsernameAndPhone(memberRegistVO.getUserName(), memberRegistVO.getPhone());
        entity.setMobile(memberRegistVO.getPhone());
        entity.setUsername(memberRegistVO.getUserName());
        entity.setNickname(memberRegistVO.getUserName());
        //加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(memberRegistVO.getPassWord());
        entity.setPassword(encode);

        //其他的默认信息
        memberDao.insert(entity);
    }

    @Override
    public void checkUsernameAndPhone(String userName, String phone) throws UserExistException {
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone).or().eq("username", userName));
        if (count>0){
            throw new UserExistException("手机号或用户名不唯一");
        }
    }

    @Override
    public MemberEntity login(MemberLoginVO memberLoginVO) {

        String loginacct = memberLoginVO.getLoginacct();
        String password = memberLoginVO.getPassword();

        //1.去数据库根据账号查询
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginacct)
                .or()
                .eq("mobile", loginacct));
        if (entity == null){
            //登陆失败
            return null;
        }else {
            //匹配密码
            String password1 = entity.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password, password1);

            if (matches){
                //登陆成功
                return  entity;
            }else {
                //密码错误
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) {
        //登录和注册合并逻辑
        String uid = socialUser.getUid();

        MemberDao memberDao = this.baseMapper;
        MemberEntity one = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (one != null){
            //存在 更换令牌
            MemberEntity entity = new MemberEntity();
            entity.setId(one.getId());
            entity.setAccessToken(socialUser.getAccess_token());
            entity.setExpiresIn(socialUser.getExpires_in());

            memberDao.updateById(entity);
            one.setAccessToken(socialUser.getAccess_token());
            one.setExpiresIn(socialUser.getExpires_in());
            return one;
        }else {
            //进行注册
            MemberEntity register = new MemberEntity();
            //3、查询当前社交用户的社交账号信息（昵称、性别等）
            Map<String,String> query = new HashMap<>();
            query.put("access_token",socialUser.getAccess_token());
            query.put("uid",socialUser.getUid());
            try {
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200){
                    //success
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    String profileImageUrl = jsonObject.getString("profile_image_url");
                    register.setNickname(name);
                    register.setGender("m".equals(gender)?1:0);
                    register.setHeader(profileImageUrl);
                    register.setCreateTime(new Date());

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            register.setSocialUid(socialUser.getUid());
            register.setAccessToken(socialUser.getAccess_token());
            register.setExpiresIn(socialUser.getExpires_in());

            //把用户信息插入到数据库中
            this.baseMapper.insert(register);
            return register;
        }
    }

}